package org.xhy.security.filter;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.StringUtils;
import org.xhy.security.token.SmsAuthenticationToken;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义短信认证
 */
public class SmsAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    //请求参数名
    private String phoneParameter = "phone";

    //只能是post请求
    private boolean postOnly = true;

    public SmsAuthenticationFilter() {
        //拦截的URL和方法
        super(new AntPathRequestMatcher("/smslogin", "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        if (this.postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("只能是POST请求");
        }

        //请求中获取phone  trim()去掉空格
        String phone = request.getParameter(phoneParameter);
        phone = StringUtils.hasText(phone)?phone.trim():"";

        //设置token
        SmsAuthenticationToken token = new SmsAuthenticationToken(phone);

        //详情
        setDetails(request,token);

        //调用认证管理器请求认证
        return this.getAuthenticationManager().authenticate(token);
    }

    public void setPostOnly(boolean postOnly) {
        this.postOnly = postOnly;
    }

    protected void setDetails(HttpServletRequest request, SmsAuthenticationToken authRequest) {
        authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
    }
}
